/*
 * Copyright 2014 JooKar (info@jookar.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.jookar.privatechat.bussiness;

import java.util.HashMap;

import nl.jookar.privatechat.model.EmailAddress;
import nl.jookar.privatechat.model.Message;
import nl.jookar.privatechat.model.User;

/**
 * The Postoffice handles the general application logic.
 * 
 * @author Joost A. Bloemsma
 */
public class PostOffice {
    private HashMap<User, MessageQueue> userQueues = new HashMap<User, MessageQueue>();
    
    /**
     * Tries to send a message to the receiver.
     * @param msg The message to be send
     * @param addrSender the email address (id) of the sender
     * @param addrReceiver the email address (id) of the receiver
     * @return A {@link Message} instance
     * @throws UnknownUserException 
     */
    public Message sendMessage(String msg, EmailAddress addrSender, EmailAddress addrReceiver) throws UnknownUserException  {
        Message message = new Message(UserRegistry.getUser(addrSender), UserRegistry.getUser(addrReceiver), msg);
        
        getUserQueue(message.getTo()).addMessage(message);
        return message;
    }
    
    private MessageQueue getUserQueue(User user) {
        MessageQueue queue = null;
        
        if (userQueues.containsKey(user)) {
            queue = userQueues.get(user); 
        } else {
            queue = new MessageQueue(user);
            userQueues.put(user, queue);
        }
        return queue;
    }
    
}

